import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_category.dart';
import 'package:flutter_learn_vi/src/bean/bean_mine.dart';
import 'package:flutter_learn_vi/src/bean/bean_news.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import 'news_item_page.dart';
import 'news_select_tab.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/11.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class NewsItemRequestPage extends StatefulWidget {
  final CategoryItemBean itemBean;

  //1为党建
  final int pageIndex;
  final MineBean mineBean;

  NewsItemRequestPage(
      {Key key, @required this.itemBean, this.pageIndex = 1, this.mineBean})
      : super(key: key);

  @override
  _NewsItemRequestPageState createState() => _NewsItemRequestPageState();
}

class _NewsItemRequestPageState extends State<NewsItemRequestPage>
    with SingleTickerProviderStateMixin {
  List<NewsBean> _list;

  bool isClickRefresh = false;

  //控制器
  TabController _tabController;

  //Tab集合
  List<Widget> tabs = <Widget>[];
  int currentSelectIndex = 0;

  @override
  void initState() {
    super.initState();
    List<CategoryItemBean> children = widget.itemBean.children;
    if (children != null && children.length > 0) {
      _tabController = new TabController(length: children.length, vsync: this);
      _tabController.addListener(() {
        currentSelectIndex = _tabController.index;
        setState(() {});
        getNewsList();
      });
    }
    getNewsList();
  }

  @override
  Widget build(BuildContext context) {
    List<CategoryItemBean> children = widget.itemBean.children;
    if (children != null && children.length > 0) {
      tabs = [];
      for (int i = 0; i < children.length; i++) {
        tabs.add(
          NewsSelectTab(
            element: children[i],
            eIndex: i,
            selectIndex: currentSelectIndex,
          ),
        );
      }
      children.forEach((element) {});
    }
    return RefreshIndicator(
      onRefresh: () async {
        await getNewsList();
        return true;
      },
      child: buildNewsItemPage(),
    );
  }

  Widget buildNewsItemPage() {
    List<CategoryItemBean> children = widget.itemBean.children;
    if (children != null && children.length > 0) {
      return Column(
        children: [
          Container(
            margin: EdgeInsets.only(top: 1),
            width: double.infinity,
            child: Material(
                color: Colors.white,
                child: TabBar(
                  indicatorColor: Colors.white,
                  //可以和TabBarView关联使用同一个TabController
                  controller: _tabController,
                  //子Tab
                  tabs: tabs,
                  isScrollable: true,
                )),
          ),
          Expanded(
            child: AnimatedSwitcher(
              //动画时间
              duration: Duration(milliseconds: 500),
              //动画曲线
              switchInCurve: Curves.easeInOutBack,
              //动画方式 这里使用中心缩放
              transitionBuilder: (child, animation) => FadeTransition(
                opacity: animation,
                child: child,
              ),
              //动画切换显示的子Widget
              child: buildNewsItem2Page(),
            ),
          ),
        ],
      );
    }
    return buildNewsItem2Page();
  }

  Widget buildNewsItem2Page() {
    if (_list == null) {
      return Center(child: LoadingWidget());
    }
    if (_list.length == 0) {
      return Center(
        child: NoDataWidget(
          clickCallBack: () {
            isClickRefresh = true;
            getNewsList();
          },
        ),
      );
    }
    return NewsItemPage(
      list: _list,
      key: ValueKey("$currentSelectIndex"),
    );
  }

  CancelToken _cancelToken;

  Future<bool> getNewsList() async {
    Map<String, dynamic> map = Map();
    if (widget.pageIndex == 1) {
      map["type"] = "FACTION";
    } else {
      map["type"] = "NEWS_INFO";
    }
    map["category"] = widget.itemBean.categoryCode;
    List<CategoryItemBean> children = widget.itemBean.children;
    if (children != null && children.length > 0) {
      map["categoryLevel"] = children[currentSelectIndex].categoryCode;
    }

    if (widget.mineBean != null) {
      map["selectMineId"] = widget.mineBean.id;
    }

    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.newsMore,
      queryParameters: map,
      cancelTag: _cancelToken,
    );

    if (responseInfo.success) {
      _list = [];
      List list = responseInfo.data;
      list.forEach((element) {
        NewsBean newsBean = NewsBean.fromJson(element);
        _list.add(newsBean);
      });
    }

    if (!mounted) return true;
    if (isClickRefresh && (_list == null || _list.length == 0)) {
      isClickRefresh = false;
      ToastUtils.showToast("已刷新");
    }
    setState(() {});

    return Future.value(true);
  }

  @override
  void dispose() {
    super.dispose();
    if (_cancelToken != null &&
        _cancelToken.isCancelled != null &&
        !_cancelToken.isCancelled) {
      _cancelToken.cancel();
    }
  }
}
